#include "db.h"
#include <json.h>
#include <QSqlDatabase>
#include <QSqlError>

using namespace Rt;

bool Db::connect(const QString &confFilename, QString *errorString, const QString &connectionName)
{
    bool ok;
    QVariantMap conf = Rt::Json::load(confFilename, &ok).toMap();
    if (!ok) {
        if (errorString)
            *errorString = "Error loading db config file";
        return false;
    }
    QSqlDatabase db = QSqlDatabase::addDatabase(conf.value("db_type").toString(), connectionName);
    db.setHostName(conf.value("host").toString());
    db.setPort(conf.value("port", "3306").toInt());
    db.setUserName(conf.value("username").toString());
    db.setPassword(conf.value("password").toString());
    db.setDatabaseName(conf.value("db_name").toString());
    db.setConnectOptions(conf.value("options").toString());
    if (db.open()) {
        return true;
    } else {
        if (errorString)
            *errorString = db.lastError().text();
        return false;
    }
}
